<?php

// +----------------------------------------------------------------------
// | 分销管家
// +----------------------------------------------------------------------
// | Copyright (c) 2015 http://www.kmeen.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: xzake <http://www.kmeen.com>
// +----------------------------------------------------------------------

namespace WeChat\Controller;

use Think\Controller;
use Think\Log;

/**
 * 后台公共控制器
 * @author xzake
 */
class PublicController extends Controller {

    protected function _initialize() {
        //读取数据库中的配置
        $config = S('DB_CONFIG_DATA');
        
        if (!$config) {
            
            $config = D('SystemConfig')->lists();
            
            S('DB_CONFIG_DATA', $config);
        }
        C($config); //添加配置
    }

    /*
     * 微信对接
     */

    public function wechat() {

        $w = D('Wechat')->find();

        $option = array(
            'token' => $w['token'],
            'appid' => $w['appid'],
            'secret' => $w['secret'],
            'aeskey' => $w['encodingaeskey']
        );

        Log::write("Wechat Init Option:" . json_encode($option));

        $wechat = new \Common\WeChat\Wechat($option);

        if ($wechat->valid()) {

            $request = $wechat->request();
            Log::write("Wechat Request:" . json_encode($request));

            $this->distributeRequest($wechat, $request);
        }
    }

    private function distributeRequest($wechat, $request) {
        Log::write("distributeRequest");

        switch ($request['msgtype']) {
            //事件
            case 'event':
                $this->distributeEvent($wechat, $request);
                break;
            //文本
            case 'text':
                $this->responseKeyword($wechat, $request['content']);
                //$wechat->response("文本");
                break;
            default:
                $wechat->response("不知道你说什么");
        }
    }

    private function distributeEvent($wechat, $request) {

        Log::write("distributeEvent===:" . json_encode($request));

        $request['event'] = strtolower($request['event']);

        switch ($request['event']) {
            //关注
            case 'subscribe':
                $this->responseSubscribe($wechat, $request);
                break;
            //自定义菜单 - 点击菜单拉取消息时的事件推送
            case 'click':
                $this->responseClick($wechat, $request);
                break;
            case 'view':
                $wechat->response("view");
                break;
            //扫描二维码
            case 'scan':
                D("Member")->saveUsers($request["fromusername"], $request['ticket']);
                //$wechat->response("您扫描二维码" . $request['ticket']);
                break;
            default:
                $wechat->response("不知道你说什么");
        }
    }

    private function responseSubscribe($wechat, $request) {

        Log::write("responseSubscribe");

        $wechat->getToken();

        $info = $wechat->user($request["fromusername"]);
        Log::write("用户信息:" . json_encode($info));

        $data['openid'] = $request["fromusername"];

        if ($info) {
            $data['nickname'] = $info['nickname'];
            $data['info'] = json_encode($info);
        }

        //二维码关注
        if (isset($request['eventkey']) && isset($request['ticket'])) {
            D("Member")->saveUsers($data, $request['ticket']);
            //$wechat->response("欢迎关注,谢谢来自二维码的关注！" . $request['ticket']);
        } else { //普通关注
            D("Member")->saveUsers($data);
            //$wechat->response("欢迎关注");
        }
        $site_name = C('WEB_SITE_TITLE');

        $sql = "select a.id,a.openid,a.`nickname`,b.nickname as fnickname from"
                . " kmeen_member as a left join"
                . "  kmeen_member as b on a.pid = b.id "
                . "where a.openid = '" . $request["fromusername"] . "'";

        $xData = M()->query($sql);
        $uData = $xData[0];
        $nickname = $uData['nickname'];
        $fnickname = $uData['fnickname'];
//        $baseUrl = C('WEB_SITE_DOMAIN');
//        $year = date("Y");
        $value  = M('system_config')->where("name = 'WEB_USER_MESSAGE_HAS_LEADER'")->field('value')->find();
        /*$text = "您好【{$nickname}】";
        if (empty($fnickname)) {
            $text = $text . "，" . '恭喜您成为' . $site_name
                    . '的第【' . $uData['id'] . '】位会员！';
        } else {
            $text = $text . "，" . '恭喜您由：【' . $fnickname . '】推荐成为'
                    . $site_name . '的第【' . $uData['id'] . '】位会员！';
        }
        */
         if (empty($fnickname)) {
           $text=C('WEB_USER_MESSAGE_NO_LEADER');         
        } else {        
          $text=$value['value'];           
           $text = str_replace("fnickname", $fnickname, $text);             
        }
          $text = str_replace("nickname", $nickname, $text);
           $text = str_replace("sitename", $site_name, $text);
           $text = str_replace("num", $uData['id'], $text);
        
        
       Log::write("文本:" . $value['value']);
       Log::write("sitename===:" . C('WEB_SITE_TITLE'));
        Log::write("用户信息:" . $text);

        $wechat->response($text);
    }

    private function saveUsers($fromusername, $ticket = FALSE) {

        $member_model = D("Member"); // 实例化User对象

        $map["openid"] = array("eq", $fromusername);

        $temp = $member_model->where($map)->find();

        if (empty($temp)) {

            $data = array();

            $data['openid'] = $fromusername;

            $data['ticket'] = $fromusername;

            if ($ticket) {

                $map = array();

                $map["ticket"] = array("eq", $ticket);

                $parent = $member_model->where($map)->find();

                if (empty($parent)) {

                    $this->saveNormalUser($data);
                } else {

                    $this->saveTicketUser($data, $parent);
                }
            } else {

                $this->saveNormalUser($data);
            }
        }
    }

    private function saveNormalUser($data) {

        $member_model = D("Member"); // 实例化User对象
        Log::write("用户普通关注");

        $data['pid'] = 0;
        $data['lft'] = 1;
        $data['rgt'] = 2;
        $data['lvl'] = 0;
        $data['flag'] = 0;
        $time = time();
        $data['create_time'] = $time;
        $data['update_time'] = $time;
        $data['status'] = 1;
        Log::write("准备写入用户信息:" . json_encode($data));
        $id = $member_model->add($data);
        if (id) {
            Log::write("写入用户信息成功:$id");
            $td["id"] = $id;
            $td["flag"] = $id;
            $member_model->save($td);
        } else {
            Log::write("写入用户信息失败");
        }
    }

    private function saveTicketUser($data, $parent) {
        $pkey = $parent['rgt'];
        $member_model = D("Member"); // 实例化User对象
        $data['pid'] = $parent['id'];
        $data['lft'] = $pkey;
        $data['rgt'] = $pkey + 1;
        $data['lvl'] = $parent['lvl'] + 1;
        $data['flag'] = $parent['flag'];
        $time = time();
        $data['create_time'] = $time;
        $data['update_time'] = $time;
        $data['status'] = 1;
        Log::write("准备写入用户信息:" . json_encode($data));
        $id = $member_model->add($data);
        if (id) {
            Log::write("写入用户信息成功:$id");
            $rmap = array();
            $rmap["flag"] = array("eq", $parent['flag']);
            $rmap["rgt"] = array("egt", $pkey);
            $rmap["id"] = array("neq", $id);

            $member_model->where($rmap)->setInc('rgt', 2);
            Log::write("更新用户关系rgt" . M()->getLastSql());
            $lmap = array();
            $lmap["flag"] = array("eq", $parent['flag']);
            $lmap["lft"] = array("gt", $pkey);
            $lmap["id"] = array("neq", $id);

            $member_model->where($lmap)->setInc('lft', 2);
            Log::write("更新用户关系lft" . M()->getLastSql());
        } else {
            Log::write("写入用户信息失败");
        }
    }

    private function responseClick($wechat, $request) {

        $this->responseKeyword($wechat, $request['eventkey']);
    }

    private function responseKeyword($wechat, $key) {

        $map['keyword'] = array('eq', $key);

        $keyword = D("Keyword")->where($map)->find();

        if (!empty($keyword)) {

            switch ($keyword['type']) {
                //关注
                case 'CustomReplyMulti':
                    $this->responseMulti($wechat, $keyword);
                    break;
                //自定义菜单 - 点击菜单拉取消息时的事件推送
                case 'CustomReplyNews':
                    $this->responseNews($wechat, $keyword);
                    break;
                case 'CustomReplyText':
                    $this->responseText($wechat, $keyword);
                    break;
                default:
                    $wechat->response("不知道你说什么" . responseClick);
            }
        } else {

            $wechat->response("熙熙家纺感谢您的参与，欢迎您提出合理化的建议。");
        }
    }

    private function responseMulti($wechat, $keyword) {

        Log::write("responseNews" . json_encode($keyword));

        $map['id'] = array('eq', $keyword['type_key']);

        $multi = D("CustomReplyMulti")->where($map)->find();

        $mmap['id'] = array('in', $multi['ids']);

        $data = D("CustomReplyNews")->where($mmap)->select();

        $news = array();

        foreach ($data as $item) {

            $news[] = array(
                $item['title'],
                $item['intro'],
                C('WEB_SITE_DOMAIN') . get_cover($item['cover']),
                C('WEB_SITE_DOMAIN') . U("WeChat/News/detail/", array("id" => $item['id']))
            );
        }

        $wechat->response($news, "news");
    }

    private function responseNews($wechat, $keyword) {

        Log::write("responseNews" . json_encode($keyword));

        $map['id'] = array('eq', $keyword['type_key']);

        $data = D("CustomReplyNews")->where($map)->find();

        $news = array();

        $news[] = array(
            $data['title'],
            $data['intro'],
            C('WEB_SITE_DOMAIN') . get_cover($data['cover']),
            C('WEB_SITE_DOMAIN') . U("WeChat/News/detail/", array("id" => $data['id']))
        );

        $wechat->response($news, "news");
    }

    private function responseText($wechat, $keyword) {

        $map['id'] = array('eq', $keyword['type_key']);

        $data = D("CustomReplyText")->where($map)->find();

        $wechat->response($data['content']);
    }

}
